package com.controller;

import com.alibaba.fastjson.JSONObject;
import com.annotation.Logging;
import com.bean.*;
import com.bean.vo.AnswerResult;
import com.bean.vo.AnswersVo;
import com.bean.vo.UsersVo;
import com.intercepter.TokenIntercepter;
import com.service.AnswerService;
import com.service.UsersService;
import com.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.swing.text.html.HTMLDocument;
import java.util.*;
import java.util.stream.Collectors;

//登录答题之CONTROLLER
@RestController
@CrossOrigin
@RequestMapping("/killNode")
public class KillNodeController {

    private Logger logger= LoggerFactory.getLogger(KillNodeController.class);

    @Autowired
    private RedisUtil redisUtil;//缓存工具类
    @Autowired
    private UsersService usersService;
    @Autowired
    private AnswerService answerService;

   // private  List<AnswersVo>myAnswersVoList;

//    //生成token
//    public static String generateToken(String userName,String password){
//       Map <String,Object> claims = new HashMap<>();
//        claims.put("userName", userName);
//        claims.put("password", password);
//      return   JWTUtils.getToken(claims);
//    }

    //通过token来获取User对象
    public  Users getUser(String token){
        Users newUser=new Users();
        String userName=  JWTSignalUtils.getTokenValue(token,"userName");
        String password=  JWTSignalUtils.getTokenValue(token,"password");

        newUser.setUserName(userName);
        newUser.setPassword(password);
        Users user= usersService.checkOne(newUser);
        return  user;
    }

    //d登录
    @RequestMapping("/login")
    @Logging
    public AjaxResult login(@RequestBody Users u, HttpServletRequest request) {
     if(StringUtils.isEmpty( u.getUserName())||StringUtils.isEmpty( u.getPassword()) ){

         return new AjaxResult(500, Constants.loginFailConstants);
     }
//
        //先从缓存里拿
        Object  userVo=redisUtil.get(Constants.userRedisConstants+u.getUserName()+u.getPassword());
        Users a=null;
        //缓存没有则查数据库
        if(StringUtils.isNull(userVo)||userVo.equals("null")){
            a = usersService.checkOne(u);
            //查数据库还没有
            if (a == null) {
                redisUtil.set(Constants.userRedisConstants+u.getUserName()+u.getPassword(),"nothing");//为防止击穿
                return new AjaxResult(300, Constants.loginFailConstants);
            }else{
                //查数据库有东西
                redisUtil.set(Constants.userRedisConstants+u.getUserName(),
                        JSONObject.toJSONString(a));//为防止击穿，将用户内容设置进缓存去
               //生成token

                String token = JWTSignalUtils.getToken(u.getUserName(),u.getPassword());
                logger.info(token);
                UsersVo uvo= new UsersVo();
                BeanUtils.copyProperties(a,uvo);
                uvo.setToken(token);
//                redisUtil.set("auto-token",
//                        token);
                //以用户名和密码作为key保存在redis中
                //后续在拦截器中
                redisUtil.set(Constants.userTokenInfo+u.getUserName()+u.getPassword(),
                      token);
                return new AjaxResult(200, Constants.loginSuccess, uvo);
            }

        }else{//缓存里面有东西
            //缓存里面有东西但是是空的
            if(userVo.toString()=="nothing"){
                return new AjaxResult(300, Constants.loginFailConstants);
            }else{//缓存有正常用户信息
                //String转化成实体类
                 UsersVo uvo= (UsersVo) JSONObject.parseObject((String)userVo,UsersVo.class) ;
                String token = JWTSignalUtils.getToken(u.getUserName(),u.getPassword());
                uvo.setToken(token);
                logger.info(token);
                redisUtil.set(Constants.userTokenInfo+u.getUserName()+u.getPassword(),
                        token);
                return new AjaxResult(200, Constants.loginSuccess, uvo);
            }

        }

    }


    //注册是也
    @RequestMapping("/registry")
    @Logging
    public AjaxResult registry(@RequestBody Users u) {
        if(StringUtils.isEmpty( u.getUserName())||StringUtils.isEmpty( u.getPassword()) ){

            return new AjaxResult(500, "请输入正确的信息");
        }
        Object userVo=  redisUtil.get(Constants.userRedisConstants+u.getUserName()+u.getPassword());
        Users a=null;
        //先看缓存有无，不存在或者s为nonthing则继续判断数据库有没有
        if(StringUtils.isNull(userVo)||userVo.toString().equals("nothing")){
            //看数据库
            a = usersService.checkOne(u);
            //如果数据库也没用则添加之，注册
            if (StringUtils.isNull(a)) {
                int i = usersService.insert(u);
                if (i > 0) {
                    //置入缓存之中
                    redisUtil.set(Constants.userRedisConstants+u.getUserName()+u.getPassword(),
                            JSONObject.toJSONString(a));
                    return new AjaxResult(200, "注册成功", u);
                } else {
                    return new AjaxResult(400, "添加失败系统异常");
                }
            }else {
                redisUtil.set(Constants.userRedisConstants+u.getUserName()+u.getPassword(),
                        JSONObject.toJSONString(a));//依然置入缓存之中
                return new AjaxResult(300, "用户已存在");
            }
        }else{//是缓存中存在数据
            return new AjaxResult(300, "用户已存在");
        }

    }

    //查询答案
    @RequestMapping("/answersInfo")
    @Logging
    @Cacheable(value = "answersVoList")
    public AjaxResult checkAllQuestions(){
        List<Questions>questions=  answerService.checkAllQuestions();
        List<Answers>answers=  answerService.checkAllAnswers();
        List<AnswersVo>answersVoList=new ArrayList<>();
        for(int i=0;i<answers.size();i++){
            AnswersVo answersVo=new AnswersVo();
            BeanUtils.copyProperties(answers.get(i),answersVo);
            Integer myid= answers.get(i).getId();
            List<Questions>myQuestions=  questions.stream().filter(
                    (e)->//因为是INTEGER所以用EQUALS
                            e.getAnswersid().equals(myid)
            ).collect(Collectors.toList());
            answersVo.setQuestions(myQuestions);
            answersVoList.add(answersVo);
        }
        //this.myAnswersVoList=answersVoList;
        return new AjaxResult(200, "查询成功",answersVoList);
    }

    //回答问题
    //返回提示文字
    //同时信息入库
    @RequestMapping("/toAnswerQuestions")
    @Logging
    public AjaxResult toAnswerQuestions(@RequestBody JSONObject result,HttpServletRequest request){
       StringBuilder stringBuilder=new StringBuilder();
       String history="";

        String nowthing = "";
        String truething = "";
        String tomorrow = "";
        String world = "";
       int sumScore=0;
       Iterator iterable= result.keySet().iterator();
        while (iterable.hasNext()){

//            logger.info(iterable.next().toString());
//            logger.info((String)result.get(iterable.next()));
           String id= (String) iterable.next();
           //默认返回来的东西，map的键是字符串类型的，因此需要用字符串取
           int score= Integer.parseInt(result.get(id).toString());
            logger.info(id +"题目");
            logger.info(score+"分数");
            List<Answers>myAnswersVoList=answerService.checkAllAnswers();
          List<Answers>answersVoList = myAnswersVoList.stream().filter(
                    (e)->e.getId().toString().equals(id)//在这里，转化为字符串才能比较
            ).collect(Collectors.toList());
          if(answersVoList.size()>0){
              if (answersVoList.get(0).getVec().equals("01")){
                  if (score< 5) {
                          history = "你对历史一窍不通,希望能够看看真实的历史";
                  } else if (score > 5
                          && score < 10
                  ) {
                          history = "你对历史有相对正常的三观";
                  } else {
                          history = "你对历史有清晰的认知，你意识到了自己的民族是谁";
                  }
                  stringBuilder.append(history);
              }else if(answersVoList.get(0).getVec().equals("02")){
                  if (score < 5) {
                      nowthing = "但是在现实被洗脑的很严重";
                  } else {
                      nowthing = "同时你对现实有清晰的认知，知道当下的环境状态";
                  }
                  stringBuilder.append(nowthing);
              }else if(answersVoList.get(0).getVec().equals("03")){
                  if (score < 5) {
                      truething = "从新冠疫苗问题最直接看你的表现，很抱歉，你的认知能力是不合格的，傻逼一样。其他的我觉得基本不用讲了。";
                  } else {
                      truething = "从新冠疫苗问题最直接看你的表现，在现实生活中，你能表现出独立思考的最基本常识性的能力";
                  }
                  stringBuilder.append(truething);
              }else if(answersVoList.get(0).getVec().equals("04")){
                  if (score < 5) {
                      tomorrow = "在对未来的判断方面，你还是对环境认知不清晰";
                  } else {
                      tomorrow = "在未来方面判断，你的想法正中要害，我很欣赏";
                  }
                  stringBuilder.append(tomorrow);
              }else if(answersVoList.get(0).getVec().equals("05")){
                  if (score < 3) {
                      world = "世界观而言，您可能还需要多读读书";
                  } else if (score > 3
                          && score < 10
                  ) {
                      world = "世界观而言，您有着不卑不亢的想法";
                  } else {
                      world = "世界观而言，您有着精彩的见解";
                  }
                  stringBuilder.append(world);
              }

          }
            sumScore=sumScore+score;
        }
        AnswerResult answerResult=new  AnswerResult();
        //根据token获取信息
        String token= request.getHeader("token");

        if(StringUtils.isNotEmpty(token)){
           Users newUser=  getUser(token);

            //入库
            KillNode killNode=new KillNode();
            killNode.setPersonid(newUser.getId().toString());
            killNode.setAnswerdate(new Date());
            killNode.setScore(sumScore);
            int k= answerService.toKillNode(killNode);
            if(k!=1){
                return new AjaxResult(500,"答题成功但入库失败",answerResult);
            }
            logger.info("信息入库成功");
            if(sumScore<30){


                //入名单
                KillList killList=new KillList();
                killList.setKillname(newUser.getName());
                killList.setKillid(newUser.getId().toString());
                int w= answerService.toKillList(killList);
                if(w!=1){
                    return new AjaxResult(500,"答题成功但入库失败",answerResult);
                }
                logger.info("死亡名单入库成功");
            }
        }



        if(sumScore<30){
            answerResult.setResultword("恐怕不是一路人，没什么好说的");
        }else{
            answerResult.setResultword(stringBuilder.toString());
        }
        logger.info(answerResult.getResultword());
        return new AjaxResult(200,"答题成功",answerResult);
    }

    @RequestMapping("/auth")
    @Logging
    public AjaxResult auth(){
        return AjaxResult.success();
    }


}
